import React from "react";
import { useState, useEffect } from 'react';
import { CRow, CCol, CFormLabel, CFormSelect } from '@coreui/react'
import { CChart } from '@coreui/react-chartjs';
import { useSelector } from 'react-redux'

const HourForecast = () => {

  const [forecastName, setForecastName] = useState([])
  const [chartData, setChartData] = useState([]);
  const [chartDataHour, setChartDataHour] = useState([]);
  const [params, setParams] = useState({
    forecast_id: 1,
    modality: null,
  });
  const token = useSelector((state) => state.token);

  const modalityitems = [
    { id: 0, name: 'Модальность' },
    { id: 1, name: 'РГ' },
    { id: 2, name: 'КТ' },
    { id: 3, name: 'МРТ' },
    { id: 4, name: 'ММГ' },
    { id: 5, name: 'Флг' },
    { id: 6, name: 'Денс' },
    { id: 7, name: 'РХ' },
    { id: 8, name: 'НДКТ' },
    { id: 9, name: 'ПЭТ/КТ' },
  ];
  
  const modalityoptions = modalityitems.map(item => ({
  label: item.name,
  value: item.id.toString(),
  }));
  
  const handleFileChange = (event) => {
    const { value } = event.target;
    setParams(prevParams => ({
      ...prevParams,
      forecast_id: value,
    }));
    fetchData();
  };
  
  const handleModalityChange = (event) => {
    const selectedModalityId = parseInt(event.target.value, 10);
    const selectedModality = modalityitems.find(item => item.id === selectedModalityId);
    if (selectedModality) {
      if (selectedModalityId === 0) {
        setParams(prevParams => ({
         ...prevParams,
          modality: null,
        }));
      } else {
        setParams(prevParams => ({
         ...prevParams,
          modality: selectedModality.name,
        }));
      }
    }
  };

  const fetchForecastName = async () => {
    try {
      const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/forecast/forecast_name`,
        {
          method: 'GET',
          headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${token}`
          },
      }
      );
      const data = await response.json();
      setForecastName(data);
    } catch (error) {
      console.error('Ошибка при получении данных:', error);
    }
  };

  const fetchData = async () => {
    let url = `${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/forecast/hour_forecast_count?`;
    if (params.forecast_id) {
      url += `&forecast_id=${params.forecast_id}`;
    }
    if (params.modality) {
      url += `&modality=${params.modality}`;
    }
  
    try {
      const response = await fetch(url,
        {
          method: 'GET',
          headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${token}`
          },
        }
      );
      const data = await response.json();
      setChartData(data);
    } catch (error) {
      console.error('Ошибка при получении данных:', error);
    }
  };

  const fetchDataHour = async () => {
    let url = `${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/forecast/hour_forecast_time?`;
    if (params.forecast_id) {
      url += `&forecast_id=${params.forecast_id}`;
    }
    if (params.modality) {
      url += `&modality=${params.modality}`;
    }
  
    try {
      const response = await fetch(url,
        {
          method: 'GET',
          headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${token}`
          },
        }
      );
      const data = await response.json();
      setChartDataHour(data);
    } catch (error) {
      console.error('Ошибка при получении данных:', error);
    }
  };

  useEffect(() => {
    fetchForecastName();
    fetchData();
    fetchDataHour();
  }, [params]);

  return (
    <>
      <h1>Почасовой прогноз</h1>
      <br></br>
      <CRow>
        <CCol xs={2}>
          <CFormLabel>Файл прогноза</CFormLabel>
        </CCol>
        <CCol xs={3}>
          <CFormSelect 
            aria-label="Выберите файл прогноза"
            options={forecastName.map(item => ({
            label: item.filename,
            value: item.id.toString(),
            }))}
            onChange={handleFileChange}
          />
        </CCol>
      </CRow>
      <br></br>
      <CRow>
        <CCol xs={2}>
            <CFormLabel>Модальность</CFormLabel>
        </CCol>
        <CCol xs={3}>
          <CFormSelect 
            aria-label="Default select example"
            options={modalityoptions}
            onChange={handleModalityChange}
          />
        </CCol>
        <CCol xs={3}></CCol>
      </CRow>
      <br></br>
      <CRow>
        <CCol>
        <CFormLabel> Прогноз количества исследований</CFormLabel>
        </CCol>
        <CCol>
        <CFormLabel> Прогноз рабочего времени, час</CFormLabel>
        </CCol>
      </CRow>
      <CRow>
      <div className="chart-container" style={{ display: 'flex', justifyContent: 'space-around' }}>
            <CChart
            className='chart'
            style ={{ width: '100%' }}
            type="bar"
            data={chartData}
            options={{
              responsive: true,
              scales: {
                x: {
                  stacked: true,
                },
                
                y: {
                  stacked: true,
                }
              }
            }}
          />
           <CChart
              className='chart'
              style ={{ width: '100%' }}
              type="bar"
              data={chartDataHour}
              options={{
                responsive: true,
                  scales: {
                    x: {
                      stacked: true,
                    },
                    y: {
                      stacked: true,
                    }
                  }
              }}
            />
        </div>
      </CRow>
    </>
)}

export default HourForecast